import React, { Component } from 'react'
import { DongbaToLocalTime, getMultiLang, base, high } from 'nc-lightapp-front'
const { BillErrorTrack } = high;
import moment from 'moment'
import './index.less';

import dataFormat from 'ssccommon/utils/dataFormat';

import dtj from '../../../image/workBenchDetailLogos/-1.png'
import bh from '../../../image/workBenchDetailLogos/0.png'
import tg from '../../../image/workBenchDetailLogos/1.png'
import spz from '../../../image/workBenchDetailLogos/2.png'

const { NCDiv } = base;
let billStatuMap = new Map()
billStatuMap.set('-1', dtj)
billStatuMap.set('0', bh)
billStatuMap.set('1', tg)
billStatuMap.set('2', spz)

import {
    nccGetTheme,
} from 'ssccommon/utils/asyncFunctions.js';

class WorkbenchDetail extends Component {
    constructor(props) {
        super();
        this.state = {
            rows: [],
            templets: {},
            multiLang: {},
            isBlackTheme: false,
            billErrorInfo: {
                show: false
            },
            refurbishFlag: 1 // 更新标志
        }
    }

    componentDidMount() {
        this.getTheme();
        getMultiLang({
            moduleId: 1056, domainName: 'sscrp', currentLocale: 'zh-CN', callback: (json) => {
                this.setState({
                    multiLang: json
                })
            }
        })
    }

    componentDidUpdate() {
        document.getElementById('WorkbenchDetail').style.height = (document.documentElement.clientHeight - document.getElementById('WorkbenchDetail').getBoundingClientRect().top - 8) + 'px'
        return true
    }

    // 获取主题
    getTheme = async () => {
        const isBlackTheme = await nccGetTheme() === 'black'
        this.setState({ isBlackTheme })
    }

    /**
     * 取得所有数据
     */
    getAllDetailData() {
        return {
            rows: this.state.rows,
            templets: this.state.templets
        }
    }

    /**
     * 清空所有数据
     */
    clearAllDetailData() {
        this.setState({
            rows: [],
            templets: {}
        });
    }

    /**
     * 刷新卡片列表
     */
    refurbishDetail() {
        // 强制更新页面
        this.setState({ refurbishFlag: this.state.refurbishFlag + 1 });
    }

    addDetailData(config, listData) {
        let oldRows = this.state.rows;
        let oldTemplets = this.state.templets;
        config.rows.map((one, index) => {
            if (listData) {
                //从列表上复制saga事务信息到detail
                const { values } = listData[index];
                one.values["saga_frozen"] = values.saga_frozen;
                one.values["saga_btxid"] = values.saga_btxid;
                one.values["saga_gtxid"] = values.saga_gtxid;
                one.values["saga_status"] = values.saga_status;
                one.values["pk_currenttask"] = values.pk_currenttask;
                one.values["pk_task"] = values.pk_task;
                one.values["ts"] = values.ts;
                one.values["module"] = values.module;
                one.values["taskstatus"] = values.taskstatus;
                one.values["iscmpreject"] = values.iscmpreject;
            }
            oldRows.push(one);
        })
        Object.assign(oldTemplets, config.templets);
        this.setState({
            rows: oldRows,
            templets: oldTemplets
        });
    }


    btnClick = (type, data) => {
        this.props.btnClick(type, data)
    }

    // 单据日期多时区处理
    getLocalTimeObject = (BeijinVal) => {
        return DongbaToLocalTime(moment(BeijinVal))
    }

    getLocalTime = (_i) => {
        let month = _i.getMonth() + 1
        if (month < 10) month = `0${month}`
        let date = _i.getDate()
        if (date < 10) date = `0${date}`
        return `${_i.getFullYear()}-${month}-${date}`
    }

    openEachTpl = idx => {
        const { rows } = this.state
        rows[idx].open = !rows[idx].open
        this.setState({ rows })
    }

    getLogo = statu => {
        let logo = null
        if (statu !== 'null') logo = billStatuMap.get(statu)
        return logo
    }
    getLogoTxt = statu => {
        if (statu == '-1') {
            return this.state.multiLang['1056image-0040']
        } else if (statu == '0') {
            return this.state.multiLang['1056image-0041']
        } else if (statu == '1') {
            return this.state.multiLang['1056image-0042']
        } else if (statu == '2') {
            return this.state.multiLang['1056image-0043']
        }
        return ''
    }
    getLogoClassName = statu => {
        let className = 'detail-logos '
        if (statu == '-1') {
            className += 'logo-dtj'
        } else if (statu == '0') {
            className += 'logo-bh'
        } else if (statu == '1') {
            className += 'logo-sptg'
        } else if (statu == '2') {
            className += 'logo-spz'
        }
        return className
    }

    handleSagaErrorClick = (rowOne) => {

        const { saga_gtxid, pk_currenttask } = rowOne.values;

        this.setState({
            billErrorInfo: {
                show: true,
                pk: (pk_currenttask && pk_currenttask.value) || "",
                gtxid: (saga_gtxid && saga_gtxid.value) || "",
            }
        });
    }

    render() {
        const { props, getBtns, buttonArea, sagasButtonVisible } = this.props;

        let getTemplateShowValue = (rowOne, templateOne, uFormat) => {
            let itemTpl = rowOne.values[templateOne.attrcode]
            if (
                itemTpl &&
                itemTpl.display
            ) {
                if (templateOne.attrcode === 'billdate') {
                    return dataFormat(itemTpl.display, 'date');

                } else if (templateOne.attrcode === 'amount') {
                    return dataFormat(itemTpl.display, 'number');
                } else {
                    return itemTpl.display
                }
            } else if (itemTpl) {
                if (itemTpl.value) {
                    if (templateOne.attrcode === 'billdate') {
                        return dataFormat(itemTpl.display, 'date')
                    } else if (templateOne.attrcode === 'amount') {
                        return dataFormat(itemTpl.value, 'number');
                    } else {
                        return itemTpl.value
                    }
                } else {
                    return null
                }
            } else {
                return null
            }
        }

        let getBtnsP = (data, index) => {
            return props.button.createOprationButton(getBtns((data || {}).values, index, (data || {}).__fullValues), {
                area: buttonArea,
                buttonLimit: 3,
                onButtonClick: (props, btnKey) => {
                    // console.log('明细按钮事件', btnKey, data, index, "detail");
                    this.props.doAction.call(this, btnKey, (data || {}).values, index, "detail", (data || {}).__fullValues)
                }
            });;
        }

        return (
            <NCDiv fieldid={(window.presetVar && window.presetVar.list) || 'bill'} areaCode={NCDiv.config.List}>
                <div
                    className={`ssc-cells u-table-body nc-theme-gray-area-bgc nc-theme-area-split-bc ssc-row-thumb-scroll-mark ${this.state.isBlackTheme ? 'workbenchdetail-black' : ''}`}
                    id="WorkbenchDetail"
                >
                    {
                        !this.state.rows.length ?
                        (<div className="card-no-data-wrap">
                            <i className="no-data"></i>
                            暂无数据
                        </div>)
                        :
                        this.state.refurbishFlag && this.state.rows.map((rowOne, index) => {
                            if (rowOne == null) {
                                return "";
                            }

                            let thisTemplate = this.state.templets[rowOne.values.pk_group.value + ':' + rowOne.tradetypecode] || this.state.templets[rowOne.tradetypecode] || [];

                            const sagaError = rowOne.values.saga_status && rowOne.values.saga_status.value === "1";

                            // 显示顺序
                            thisTemplate.sort((a, b) => a.position - b.position)
                            thisTemplate = thisTemplate.filter(templateOne => templateOne.visible && templateOne.attrcode !== 'billno')
                            const thisTemplateLen = thisTemplate.length
                            if (!rowOne.open && thisTemplateLen > 3) {
                                thisTemplate.length = 3
                            }
                            let rollbackClassName = "";
                            let getBillNoLink = (rowOne, index) => {
                                if (rowOne != null && rowOne.values != null && rowOne.values.billno && rowOne.values.billno.value != null) {
                                    let ret = [
                                        (
                                            <a
                                                className="billnoa"
                                                onClick={this.props.doAction.bind(this, "OpenBill", rowOne.values, index, "detail", rowOne.__fullValues)}>
                                                {rowOne.values.billno.value}
                                            </a>
                                        )
                                    ]
                                    // if (rowOne.values.urgent && rowOne.values.urgent.value == 'Y') {
                                    //     ret.push(<span className="billno-reject">{this.state.multiLang['1056common-0022']/*紧急*/}</span>)
                                    // }
                                    // if (rowOne.values.isreject && rowOne.values.isreject.value == 'Y') {
                                    //     ret.push(<span className="billno-reject">{this.state.multiLang['1056common-0023']/*驳回*/}</span>)
                                    // }
                                    // if(rowOne.values.ismereject && rowOne.values.ismereject.value == 'Y'){
                                    //     ret.push(<span className="billno-reject">{this.state.multiLang['1056common-0024']/*本人驳回*/}</span>)
                                    // }
                                    // if(rowOne.values.isleaderreject && rowOne.values.isleaderreject.value == 'Y'){
                                    //     ret.push(<span className="billno-reject">{this.state.multiLang['1056common-0025']/*上级驳回*/}</span>)
                                    // }
                                    // if (rowOne.values.isappointed && rowOne.values.isappointed.value == 'Y') {
                                    //     ret.push(<span className="billno-reject">{this.state.multiLang['1056common-0026']/*强制分配*/}</span>)
                                    // } 
                                    return ret
                                } else {
                                    return null
                                }
                            }

                            const { values: { approvestatus, apply_org = {}, billno = {}, pk_tradetype = {} } } = rowOne
                            const logo = approvestatus ? this.getLogo(approvestatus.value) : null
                            let fieldIdItemArr = [];

                            pk_tradetype.display && fieldIdItemArr.push(pk_tradetype.display);
                            apply_org.display && fieldIdItemArr.push(apply_org.display);
                            billno.value && fieldIdItemArr.push(billno.value);

                            const eachSectionContent = [[]]
                            let pushedBillNo = false, sumColnumNum = 0
                            thisTemplate.forEach((templateOne, templateIndex) => {
                                if (!pushedBillNo) {
                                    // 单据编码
                                    eachSectionContent[eachSectionContent.length - 1].push(
                                        <li className='item-template-1' fieldid='bill-no'>
                                            <span title={this.state.multiLang['1056common-0027']} className="field-key nc-theme-form-label-c">
                                                {this.state.multiLang['1056common-0027']}
                                            </span>
                                            <span className='nc-theme-form-label-c field-colon'>{'：'}</span>
                                            <span
                                                className="field-value"
                                                title={rowOne.values.billno && rowOne.values.billno.value}
                                            >
                                                {getBillNoLink(rowOne, index)}
                                            </span>
                                        </li>
                                    )
                                    ++sumColnumNum
                                    pushedBillNo = true
                                }
                                if (templateOne.colnum + sumColnumNum > 4) {
                                    sumColnumNum = 0
                                    eachSectionContent.push([])

                                    eachSectionContent[eachSectionContent.length - 1].push(
                                        <li
                                            fieldid={templateOne.attrcode}
                                            key={"thisTemplate_" + templateIndex}
                                            className={'item-template-' + templateOne.colnum}
                                        >
                                            <span title={templateOne.label} className="field-key nc-theme-form-label-c">
                                                {templateOne.label}
                                            </span>
                                            <span className='nc-theme-form-label-c field-colon'>{'：'}</span>
                                            <span
                                                className="field-value nc-theme-common-font-c"
                                                title={getTemplateShowValue(rowOne, templateOne)}
                                            >
                                                {
                                                    getTemplateShowValue(rowOne, templateOne)
                                                }
                                            </span>
                                        </li>
                                    )
                                    sumColnumNum += templateOne.colnum
                                } else {
                                    eachSectionContent[eachSectionContent.length - 1].push(
                                        <li
                                            fieldid={templateOne.attrcode}
                                            key={"thisTemplate_" + templateIndex}
                                            className={'item-template-' + templateOne.colnum}
                                        >
                                            <span title={templateOne.label} className="field-key nc-theme-form-label-c">
                                                {templateOne.label}
                                            </span>
                                            <span className='nc-theme-form-label-c field-colon'>{'：'}</span>
                                            <span
                                                className="field-value nc-theme-common-font-c"
                                                title={getTemplateShowValue(rowOne, templateOne)}
                                            >
                                                {
                                                    getTemplateShowValue(rowOne, templateOne)
                                                }
                                            </span>
                                        </li>
                                    )
                                    sumColnumNum += templateOne.colnum
                                }
                            })
                            let amountF = dataFormat(rowOne.values.amount && rowOne.values.amount.value || '', 'number');
                            return (
                                <NCDiv fieldid={`${fieldIdItemArr.join('_')}`} areaCode={NCDiv.config.ListItem}>
                                    <div className={rollbackClassName + " ssc-cell nc-theme-zrow-bgc nc-theme-area-split-bc"} key={"detailArray_" + index}>
                                        <div className="cell-top">
                                            <span className='pk_tradetype nc-theme-common-font-c' fieldid="pk_tradetype">{rowOne.values.pk_tradetype.display}</span>
                                            <span className='remark nc-theme-common-font-c' fieldid="remark" title={rowOne.values.remark && rowOne.values.remark.display}>{rowOne.values.remark && rowOne.values.remark.display}</span>
                                            <span
                                                className='amount'
                                                fieldid="amount"
                                                title={`${rowOne.values.pk_currtype && rowOne.values.pk_currtype.display || ''} ${rowOne.values.amount && rowOne.values.amount.value || ''}`}>
                                                {`${rowOne.values.pk_currtype && rowOne.values.pk_currtype.display || ''}`}{amountF}
                                            </span>
                                            {/* 索引图标 */}
                                            <span className='detail-idx'>{index + 1}</span>
                                            {
                                                sagasButtonVisible && sagaError &&
                                                <span className='error-flag iconfont icon icon-gantanhao' onClick={this.handleSagaErrorClick.bind(this, rowOne)}></span>
                                            }
                                        </div>
                                        <div className="cell">
                                            <table>
                                                <tbody>
                                                    <tr>
                                                        <td style={{ paddingRight: logo ? '315px' : '230px' }}>
                                                            <section className='clearfix each-cell-content'>
                                                                {
                                                                    eachSectionContent.map(each => (
                                                                        <ul className='clearfix'>
                                                                            {[...each]}
                                                                        </ul>
                                                                    ))
                                                                }
                                                            </section>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                            {/* 点击展开三角 */}
                                            <div className="card-triangle-btn-wrap"
                                                onClick={() => { this.openEachTpl(index) }}
                                            >
                                                <span
                                                    fieldid='open-all'
                                                    className={rowOne.open ? 'open-all--details open-all--rotate' : 'open-all--details'}
                                                    style={{ display: thisTemplateLen > 3 ? 'inline-block' : 'none' }}
                                                ></span>
                                            </div>

                                        </div>
                                        {/* 单据状态图标 */}
                                        {logo && (<div fieldid="bill-status" className={this.getLogoClassName(approvestatus.value)} style={{ backgroundImage: `url(${logo})` }}>
                                            {this.getLogoTxt(approvestatus.value)}
                                        </div>)}
                                        {/* 按钮及状态图标 */}
                                        <div className="get-btns">
                                            {getBtnsP(rowOne, index)}
                                        </div>
                                    </div>

                                </NCDiv>
                            )
                        })
                    }
                    <BillErrorTrack
                        {...this.state.billErrorInfo}

                        close={() => this.setState({
                            billErrorInfo: {
                                show: false
                            }
                        })}
                    />
                </div>
            </NCDiv>
        )
    }
}
export default WorkbenchDetail;
